import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 懒加载普通页面
const AboutView = () => import('../views/AboutView.vue')
const LibraryView = () => import('../views/LibraryView.vue')
const SearchView = () => import('../views/SearchView.vue')
const PlaylistsView = () => import('../views/PlaylistsView.vue')
const FavoritesView = () => import('../views/FavoritesView.vue')
const RecentView = () => import('../views/RecentView.vue')
const RecommendedView = () => import('../views/RecommendedView.vue')
const CategoriesView = () => import('../views/CategoriesView.vue')
const CategoryView = () => import('../views/CategoryView.vue')

// 懒加载用户页面
const UserLoginView = () => import('../views/users/LoginView.vue')
const UserRegisterView = () => import('../views/users/RegisterView.vue')
const UserSettingsView = () => import('../views/users/SettingsView.vue')

// 懒加载管理员页面
const AdminLoginView = () => import('../views/admin/LoginView.vue')
const AdminDashboardView = () => import('../views/admin/DashboardView.vue')
const AdminUsersView = () => import('../views/admin/UsersView.vue')
const AdminMusicView = () => import('../views/admin/MusicView.vue')
const AdminCategoriesView = () => import('../views/admin/CategoriesView.vue')

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  },
  {
    path: '/library',
    name: 'library',
    component: LibraryView
  },
  {
    path: '/search',
    name: 'search',
    component: SearchView
  },
  {
    path: '/playlists',
    name: 'playlists',
    component: PlaylistsView
  },
  {
    path: '/favorites',
    name: 'favorites',
    component: FavoritesView
  },
  {
    path: '/recent',
    name: 'recent',
    component: RecentView
  },
  {
    path: '/recommended',
    name: 'recommended',
    component: RecommendedView
  },
  {
    path: '/categories',
    name: 'categories',
    component: CategoriesView
  },
  {
    path: '/category/:id',
    name: 'category',
    component: CategoryView
  },
  // 用户路由
  {
    path: '/users/login',
    name: 'login',
    component: UserLoginView,
    meta: { requiresGuest: true }
  },
  {
    path: '/login',
    redirect: '/users/login'
  },
  {
    path: '/users/register',
    name: 'register',
    component: UserRegisterView,
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    redirect: '/users/register'
  },
  {
    path: '/users/settings',
    name: 'settings',
    component: UserSettingsView,
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    redirect: '/users/settings'
  },
  // 管理员路由
  {
    path: '/admin',
    redirect: '/admin/login'
  },
  {
    path: '/admin/login',
    name: 'admin-login',
    component: AdminLoginView,
    meta: { requiresGuest: true, isAdmin: true }
  },
  {
    path: '/admin/dashboard',
    name: 'admin-dashboard',
    component: AdminDashboardView,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/users',
    name: 'admin-users',
    component: AdminUsersView,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/music',
    name: 'admin-music',
    component: AdminMusicView,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/categories',
    name: 'admin-categories',
    component: AdminCategoriesView,
    meta: { requiresAuth: true, requiresAdmin: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 分别检查前台和后台token
  const userToken = localStorage.getItem('userToken')
  const adminToken = localStorage.getItem('adminToken')
  const userExpiry = localStorage.getItem('userTokenExpiry')
  const adminExpiry = localStorage.getItem('adminTokenExpiry')
  const isAdminRoute = to.path.startsWith('/admin')
  
  // 检查token是否有效（未过期）
  const isUserLoggedIn = userToken && userExpiry && Date.now() < parseInt(userExpiry)
  const isAdminLoggedIn = adminToken && adminExpiry && Date.now() < parseInt(adminExpiry)
  
  console.log('路由守卫检查:', {
    to: to.path,
    from: from.path,
    hasUserToken: !!userToken,
    hasAdminToken: !!adminToken,
    isUserLoggedIn,
    isAdminLoggedIn,
    isAdminRoute,
    routeMeta: to.meta
  })
  
  // 管理员路由处理
  if (isAdminRoute) {
    // 检查是否需要管理员权限
    if (to.matched.some(record => record.meta.requiresAdmin)) {
      if (!isAdminLoggedIn) {
        // 管理员未登录或token过期，跳转到管理员登录页
        console.log('管理员未登录或token过期，跳转到管理员登录页')
        next({ name: 'admin-login' })
        return
      }
    }
    
    // 管理员登录页面 - 如果管理员已登录，跳转到仪表板
    if (to.name === 'admin-login' && isAdminLoggedIn) {
      console.log('管理员已登录，跳转到仪表板')
      next({ name: 'admin-dashboard' })
      return
    }
  } else {
    // 前台路由处理
    
    // 检查是否需要前台用户认证
    if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!isUserLoggedIn) {
        // 前台用户未登录或token过期，跳转到前台登录页
        console.log('前台用户未登录或token过期，跳转到前台登录页')
        next({ name: 'login' })
        return
      }
    }
    
    // 前台登录/注册页面 - 如果前台用户已登录，跳转到首页
    if (to.matched.some(record => record.meta.requiresGuest) && isUserLoggedIn) {
      console.log('前台用户已登录，跳转到首页')
      next({ name: 'home' })
      return
    }
  }
  
  console.log('路由守卫通过，继续导航')
  next()
})

export default router
